package com.example.administrator.xtu_community.activity;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.administrator.xtu_community.R;
import com.example.administrator.xtu_community.bean.Note;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * @author liuyuxuan
 * 添加筆記 Activity
 */
public class AddNoteActivity extends AppCompatActivity {
    public static final int FROM_ALBUM = 2;
    private ImageView addImage;
    private LinearLayout container;
    private Button input;
    private EditText add_title;
    private EditText add_content;
    List<String> imageList = new ArrayList<>();

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_note);
        initView();

        addImage.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(AddNoteActivity.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(AddNoteActivity.this, new
                        String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
            openAlbum();
        });
    }

    private void initView() {
        addImage = findViewById(R.id.add_image);
        container = findViewById(R.id.add_note_container);
        input = findViewById(R.id.add_note_input);
        add_title = findViewById(R.id.add_note_title);
        add_content = findViewById(R.id.add_note_text);
        input.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Note note = new Note();
                note.setNote_from(2);
                note.setImage2(imageList.get(0));
                Log.d("TAG", "onClick: " + imageList.size());
                note.getImage2List().addAll(imageList);
                Log.d("TAG", "onClick: " + note.getImage2List().size());
                note.setTitle(add_title.getText().toString());
                note.setContent(add_content.getText().toString());
                note.saveThrows();
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
                Toast.makeText(AddNoteActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    /**
     * 打開相冊
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(intent, FROM_ALBUM);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == FROM_ALBUM) {
                assert data != null;
                Uri uri = data.getData();
                Bitmap bitmap = null;
                try {
                    bitmap = imageSizeCompress(uri);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                imageList.add(uri.toString());
                BitmapDrawable bd = new BitmapDrawable(bitmap);
                containerAddView(bitmap);
            }
        }

    }

    /**
     * 頂部圖片Container添加一張圖
     */
    private void containerAddView(Bitmap bitmap) {
        ImageView child = new ImageView(AddNoteActivity.this);
        child.setImageBitmap(bitmap);
        child.setBackground(ContextCompat.getDrawable(AddNoteActivity.this, R.drawable.add_image_bg));
        child.setLayoutParams(new ViewGroup.LayoutParams(600, ViewGroup.LayoutParams.MATCH_PARENT));
        child.setScaleType(ImageView.ScaleType.FIT_XY);
        container.addView(child, 0);
    }

    /**
     * 把URI轉換為Bitmap圖片
     */
    private Bitmap imageSizeCompress(Uri uri) {
        InputStream stream = null;
        InputStream inputStream = null;
        try {
            //根据uri获取图片的流
            inputStream = getContentResolver().openInputStream(uri);
            BitmapFactory.Options options = new BitmapFactory.Options();
            //options的in系列的设置了，injustdecodebouond只解析图片的大小，而不加载到内存中去
            options.inJustDecodeBounds = true;
            //1.如果通过options.outHeight获取图片的宽高，就必须通过decodestream解析同options赋值
            //否则options.outheight获取不到宽高
            BitmapFactory.decodeStream(inputStream, null, options);
            //以屏幕的宽高进行压缩
            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
            int heightPixels = displayMetrics.heightPixels;
            int widthPixels = displayMetrics.widthPixels;
            //获取图片的宽高
            int outHeight = options.outHeight;
            int outWidth = options.outWidth;
            //heightPixels就是要压缩后的图片高度，宽度也一样
            int a = (int) Math.ceil((outHeight / (float) heightPixels));
            int b = (int) Math.ceil(outWidth / (float) widthPixels);
            //比例计算,一般是图片比较大的情况下进行压缩
            int max = Math.max(a, b);
            if (max > 1) {
                options.inSampleSize = max;
            }
            //解析到内存中去
            options.inJustDecodeBounds = false;
//            根据uri重新获取流，inputstream在解析中发生改变了
            stream = getContentResolver().openInputStream(uri);
            return BitmapFactory.decodeStream(stream, null, options);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

}